<?php
/**
 * 会员管理
 */

namespace App\backend\controllers\member;

use App\backend\services\MemberServices;
use App\backend\models\MemberModel as Member;
use App\backend\controllers\AdminBaseController;
use App\backend\services\RoleServices;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Validator;
use App\Utils\JsonResp;

class MemberController extends AdminBaseController
{

    protected $memberServices;

    public function __construct(MemberServices $memberServices)
    {
        $this->memberServices = $memberServices;
    }

    /**
     * 个人信息
     */
    public function getInfo()
    {
        //获取解析后的token信息;
        $data = auth('backend')->user();

        if (!$data) {
            return JsonResp::error('获取个人信息失败');
        }

        $data['role'] = RoleServices::getRoleUser($data['id']);
        $data['lastvisit_time'] = date('Y-m-d H:i:s', $data['lastvisit_time']);
        $data['avatar'] = $data['avatar']?get_host().$data['avatar']:'';
        unset($data['password'],$data['remember_token']);
        return JsonResp::success('操作成功',$data);
    }

    /**
     * 登出
     */
    public function doLogout()
    {
        auth('backend')->logout();
        return JsonResp::success('退出成功');
    }

    /**
     * 会员列表
     */
    public function list(Request $request)
    {
        $request = $request->all();
        $result = $this->memberServices->list($request);
        return successJson('成功！', $result);

    }

    /**
     * 会员详情
     */
    public function getDetails(Request $request)
    {
        $request = $request->all();
        $result = $this->memberServices->getDetails($request);
        return successJson('成功！', $result);

    }

    /**
     * 添加会员
     */
    public function addMember(Request $request)
    {
        $request = $request->all();
        $validator = Validator::make(
            $request,
            Member::rules(),
            Member::message()
        );
        if ($validator->fails()) {
            $msg = $validator->errors()->all();
            return JsonResp::error($msg[0]);
        }
        $result = $this->memberServices->addMember($request);
        return successJson('成功！', $result);
    }

    /**
     * 编辑会员
     */
    public function editMember(Request $request)
    {
        $request = $request->all();
        $result = $this->memberServices->editMember($request);
        return successJson('成功！', $result);
    }

    /**
     * 删除会员
     */
    public function deleteMember(Request $request)
    {
        $request = $request->all();
        $result = $this->memberServices->deleteMember($request);
        return successJson('成功！', $result);
    }

}
